<?php
class RegistrationForm {
	private $username;
	private $email;
	private $password;
	private $repeatPassword;
	private $city;
	private $cityId;
	private $footballRole;
	private $footballRoles = array (
			"1" => "Неактивен",
			"2" => "Любител",
			"3" => "Аматьор",
			"4" => "Професионалист" 
	);
	private $league;
	private $leagueId;
	private $team;
	private $teamId;
	private $favoriteTeam;
	private $favTeamId;
	private $messages = array ();
	private $state = true;
	private $token;
	public function __construct(array $request) {
		if (isset ( $request ['submit2'] ) && $_SERVER ['REQUEST_METHOD'] == 'POST') {
			
			$this->setUsername ( $request ['username'] );
			$this->setEmail ( $request ['email'] );
			$this->setPassword ( $request ['password'] );
			$this->setRepeatPassword ( $request ['password2'] );
			$this->setCity ( $request ['city'] );
			$this->setFootballRole ( $request ['role'] );
			
			if (isset ( $request ['league'] )) {
				
				$this->setLeagueId ( $request ['league'] );
			} else {
				$this->setLeagueId ( 9 );
			}
			
			if (isset ($request ['team']))
			{
				$this->setTeamId ( $request ['team'] );
			} else {
				$this->setTeamId ( 5 );
			}
			
			$this->setFavoriteTeam ( $request ['favorite-team'] );
			$this->validateForm ();
			
			if ($this->state == true) {
				$this->process ();
			}
		}
	}
	public function renderResponse() {
		$this->renderHead ();
		$this->renderForm ();
	}
	public function renderHead() {
		echo '<!DOCTYPE html>
              <html>
              <head>
			  <meta charset="UTF-8">
			  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
			  <script src="scipts/Reg_User_Check.js">
			  </script>
				<script>
				$(document).ready(function() {
					$("#role").change(function() {
     				if($(this).val() == 1)
				{
				$("#league").prop("disabled", "disabled");
				$("#team").prop("disabled", true);

	            }
				else 
				{
				$("#league").removeAttr("disabled");
						$("#team").prop("disabled", false);
	            }
					});
				});
				</script>
			  <link type="text/css" rel="stylesheet" href="styles/index.css"></link>
			  </head>';
	}
	public function renderForm() {
		echo '<body><div id="overlay">
		      <div id="regForm">
		      <form action="" method="post" name="register" id="register">
		      <fieldset>
		      <legend>Регистрация</legend>';
		
		$this->renderUsername ();
		$this->renderEmail ();
		$this->renderPassword ();
		$this->renderRepeatPassword ();
		$this->renderCity ();
		$this->renderFootballRole ();
		$this->renderLeague ();
		$this->renderTeam ();
		$this->renderFavoriteTeam ();
		
		echo '<input type="submit" value="Регистрирай ме" id="submit2" name="submit2"/>
			   </fieldset>
			   </form>
			   </div>
		       </div>
	           </div></body>';
	}
	private function renderUsername() {
		echo '<div id="username-div">
			  <label for="username">Потребителско име: </label> 
			  <input id="username" type="text" name="username"  value="' . $this->getUsername () . '"/>';
		if (isset ( $this->messages ['username'] )) {
			echo '<div class="error_msg">' . $this->messages ['username'] . '</div>';
		}
		echo '<div id="user_empty"></div>
			  </div>';
	}
	private function renderEmail() {
		echo '<div id="email-div">
			  <label for="email">Имейл адрес: </label>
			  <input id="email" type="text" name="email" value="' . $this->getEmail () . '"/>';
		if (isset ( $this->messages ['email'] )) {
			echo '<div class="error_msg">' . $this->messages ['email'] . '</div>';
		}
		echo '<div id="email_empty"></div>
			  </div>';
	}
	private function renderPassword() {
		echo '<div id="password-div">
			  <label for="password">Парола: </label>
			  <input id="password" type="password" name="password" value="' . $this->getPassword () . '"/>';
		if (isset ( $this->messages ['password'] )) {
			echo '<div class="error_msg">' . $this->messages ['password'] . '</div>';
		}
		echo '<div id="password_empty"></div>
			  </div>';
	}
	private function renderRepeatPassword() {
		echo '<div id="password2-div">
			  <label for="password2">Повтори паролата: </label>
			  <input id="password2" type="password" name="password2" value="' . $this->getRepeatPassword () . '"/>';
		if (isset ( $this->messages ['password2'] )) {
			echo '<div class="error_msg">' . $this->messages ['password2'] . '</div>';
		}
		echo '<div id="repeatPassword_empty"></div>
			  </div>';
	}
	private function renderCity() {
		echo '<div id="city-div">
			  <label for="city">Град: </label> 
			  <input id="city" type="text" name="city" value="' . $this->getCity () . '"/>';
		if (isset ( $this->messages ['city'] )) {
			echo '<div class="error_msg">' . $this->messages ['city'] . '</div>';
		}
		echo '<div id="city_empty"></div>
			  </div>';
	}
	private function renderFootballRole() {
		echo '<div id="role-div">
		<label for="role">Футболна заетост: </label> <select name="role" id="role">';
		
		echo '<option value="0"></option>';
		
		foreach ( $this->footballRoles as $key => $value ) {
			echo "<option value=\"$key\" ";
			
			if (isset ( $this->footballRole )) {
				if ($this->footballRole == $key)
					echo 'selected = "selected"';
			}
			echo ">$value</option>";
		}
		echo '</select>';
		
		if (isset ( $this->messages ['role'] )) {
			echo '<div class="error_msg">' . $this->messages ['role'] . '</div>';
		}
		echo '<div id="role_empty"></div>
			  </div>';
	}
	public function renderLeague() {
		echo '<div id="league-div">
		      <label for="league">Лига, в която се състезавате: </label>
			  <select id="league" name="league">';
		echo '<option value="0"></option>';
		
		$connection = DBConnection::getDBConnection ();
		$stmt = "SELECT division_id, division_name FROM division";
		
		$statement = $connection->prepare ( $stmt );
		$statement->execute ();
		
		$result = $statement->fetchAll ();
		
		foreach ( $result as $row ) {
			echo "<option value=\"" . $row ['division_id'] . "\"";
			
			if ($this->getLeague () == $row ['division_id'])
				echo 'selected="selected"';
			echo ">" . $row ['division_name'] . "</option>";
		}
		echo '</select></p>';
		
		if (isset ( $this->messages ['league'] )) {
			echo '<div class="error_msg">' . $this->messages ['league'] . '</div>';
		}
		echo '<div id="league_empty"></div>
			  </div>';
	}
	public function renderTeam() {
		echo '<div id="team-div">
			  <label for="team">Отбор, в който се състезавате: </label>
			  <input id="team" type="text" name="team" value="' . $this->getTeam () . '"/>';
		if (isset ( $this->messages ['team'] )) {
			echo '<div class="error_msg">' . $this->messages ['team'] . '</div>';
		}
		echo '<div id="team_empty"></div>
			  </div>';
	}
	public function renderFavoriteTeam() {
		echo '<div id="favoriteTeam-div">
		      <label for="favorite-team">Любим отбор: </label>
			  <input id="favorite-team" type="text" name="favorite-team" value="' . $this->getFavoriteTeam () . '"/>';
		if (isset ( $this->messages ['favorite-team'] )) {
			echo '<div class="error_msg">' . $this->messages ['favorite-team'] . '</div>';
		}
		echo '<div id="favoriteTeam_empty"></div>
			  </div>';
	}
	
	// getters
	public function getUsername() {
		return $this->username;
	}
	public function getEmail() {
		return $this->email;
	}
	public function getPassword() {
		return $this->password;
	}
	public function getRepeatPassword() {
		return $this->repeatPassword;
	}
	public function getCity() {
		return $this->city;
	}
	public function getCityId() {
		return $this->cityId;
	}
	public function getFootballRole() {
		return $this->footballRole;
	}
	public function getLeague() {
		return $this->league;
	}
	public function getLeagueId() {
		return $this->leagueId;
	}
	public function getTeam() {
		return $this->team;
	}
	public function getTeamId() {
		return $this->teamId;
	}
	public function getFavoriteTeam() {
		return $this->favoriteTeam;
	}
	public function getFavTeamId() {
		return $this->favTeamId;
	}
	
	// setters
	public function setUsername($username) {
		if ($username == "" || $username == null) {
			$this->messages ['username'] = "Въведете потребителското си име!";
			$this->state = false;
			return;
		}
		
		if (! is_string ( $username )) {
			$this->messages ['username'] = "Невалидно потребителско име";
			$this->state = false;
			return;
		}
		
		$connection = DBConnection::getDBConnection ();
		
		$statement = "SELECT user_name
					    FROM user";
		
		$stmt = $connection->prepare ( $statement );
		
		$stmt->execute ();
		
		while ( $row = $stmt->fetch () ) {
			if ($row ['user_name'] == $username) {
				$this->messages ['username'] = "Потребителското име вече е заето!";
				$this->state = false;
				return;
			}
		}
		
		$this->username = $username;
	}
	public function setEmail($email) {
		if ($email == "" || $email == null) {
			$this->messages ['email'] = "Въведете имейл!";
			$this->state = false;
			return;
		}
		
		if (! is_string ( $email )) {
			$this->messages ['email'] = "Невалиден имейл";
			$this->state = false;
			return;
		}
		
		$regex = "/([a-z0-9_]+|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i";
		if (! preg_match ( $regex, $email )) {
			
			$this->messages ['email'] = "Невалиден имейл";
			$this->state = false;
			return;
		}
		
		$connection = DBConnection::getDBConnection ();
		
		$statement = "SELECT email
					    FROM user";
		
		$stmt = $connection->prepare ( $statement );
		
		$stmt->execute ();
		
		while ( $row = $stmt->fetch () ) {
			if ($row ['email'] == $email) {
				$this->messages ['email'] = "Вече има регистриран потребител с този имейл!";
				$this->state = false;
				return;
			}
		}
		
		$this->email = $email;
	}
	public function setPassword($password) {
		if ($password == "" || $password == null) {
			$this->messages ['password'] = "Въведете парола!";
			$this->state = false;
			return;
		}
		
		if (! is_string ( $password )) {
			$this->messages ['password'] = "Невалидна парола";
			$this->state = false;
			return;
		}
		
		if (strlen ( $password ) < 6) {
			$this->messages ['password'] = "Въведете поне 6 символа!";
			$this->state = false;
			return;
		}
		
		$this->password = $password;
	}
	public function setRepeatPassword($repeatPassword) {
		if ($repeatPassword == "" || $repeatPassword == null) {
			$this->messages ['password2'] = "Повторете паролата!";
			$this->state = false;
			return;
		}
		
		if (! is_string ( $repeatPassword )) {
			$this->messages ['password2'] = "Невалидна парола";
			$this->state = false;
			return;
		}
		
		if (strlen ( $repeatPassword ) < 6) {
			$this->messages ['password2'] = "Въведете поне 6 символа!";
			$this->state = false;
			return;
		}
		
		$this->repeatPassword = $repeatPassword;
	}
	public function setCity($city) {
		if ($city == "" || $city == null) {
			$this->messages ['city'] = "Въведете град!";
			$this->state = false;
			return;
		}
		
		if (! is_string ( $city ) || (is_numeric ( $city ))) {
			$this->messages ['city'] = "Невалиден град";
			$this->state = false;
			return;
		}
		
		$this->city = $city;
	}
	public function setCityId($city) {
		$connection = DBConnection::getDBConnection ();
		
		$checkCity = "SELECT city_id
				      FROM city
				      WHERE city_name = :CITY_STR";
		
		$checkCityStr = $connection->prepare ( $checkCity );
		$checkCityStr->bindValue ( ":CITY_STR", $city, PDO::PARAM_STR );
		$checkCityStr->execute ();
		$this->cityId = 0;
		
		while ( $row = $checkCityStr->fetch () ) {
			$this->cityId = $row ['city_id'];
		}
		if ($this->cityId == 0) {
			$insertCity = "INSERT INTO city (city_name ) VALUES (:CITY)";
			$insert = $connection->prepare ( $insertCity );
			$insert->bindValue ( ":CITY", $city, PDO::PARAM_STR );
			$insert->execute ();
			
			$checkCity = "SELECT city_id
				      FROM city
				      WHERE city_name = :CITY_STR";
			
			$checkCityStr = $connection->prepare ( $checkCity );
			$checkCityStr->bindValue ( ":CITY_STR", $city, PDO::PARAM_STR );
			$checkCityStr->execute ();
			
			while ( $row = $checkCityStr->fetch () ) {
				$this->cityId = $row ['city_id'];
			}
		}
	}
	

	public function setFootballRole($footballRole) {
		if ($footballRole == "0") {
			$this->messages ['role'] = "Изберете активност!";
			$this->state = false;
		}
		$this->footballRole = $footballRole;
	}
	
	public function setLeagueId($league) {
		
		if ($this->getFootballRole () != "1" && $league == "0") {
			$this->messages ['league'] = "Изберете лига!";
		$this->state = false;
		}
			
 	$this->leagueId = $league;
	}
	
	public function setLeague($league) {
		
		if ($this->getFootballRole () != "1" && $league == "0") {
			$this->messages ['league'] = "Изберете лига!";
			$this->state = false;
		} elseif ($this->getFootballRole () == "1") {
			$this->setLeague ( 9 ); // prazen zapis za division; v tabl. division s id 9 e prazen zapis
		}                                 
		
		$this->league = $league;

	}
	public function setTeam($team) {
		if ($this->getFootballRole () != "1" && ($team == "" || $team == null)) {
			$this->messages ['team'] = "Въведете отбор!";
			$this->state = false;
			return;
		} elseif ($this->getFootballRole () == "1") {
			$this->setTeamId ( 5 ); // prazen zapis za otbor - pri men se zapisva 
			                                   // 5 poleto za playing_club 
		}
		$this->team = $team;
	}
	public function setTeamId($team) {
		
		if ($this->getFootballRole () != "1" && ($team == "" || $team == null)) {
			$this->messages ['team'] = "Въведете отбор!";
			$this->state = false;
			return;
		}
		
		$connection = DBConnection::getDBConnection ();
		
		$checkClub = "SELECT club_id
				      FROM club
				      WHERE club_name = :CLUB_STR";
		
		$checkClubStr = $connection->prepare ( $checkClub );
		$checkClubStr->bindValue ( ":CLUB_STR", $team, PDO::PARAM_STR );
		$checkClubStr->execute ();
		$this->teamId = 0;
		
		while ( $row = $checkClubStr->fetch () ) {
			$this->teamId = $row ['club_id'];
		}
		if ($this->teamId == 0) {
			$insertClub = "INSERT INTO club (club_name ) VALUES (:CLUB_STR)";
			$insert = $connection->prepare ( $insertClub );
			$insert->bindValue ( ":CLUB_STR", $team, PDO::PARAM_STR );
			$insert->execute ();
			
			$checkCity = "SELECT club_id
				      FROM club
				      WHERE club_name = :CLUB_STR";
			
			$checkClubStr = $connection->prepare ( $checkClub );
			$checkClubStr->bindValue ( ":CLUB_STR", $team, PDO::PARAM_STR );
			$checkClubStr->execute ();
			
			while ( $row = $checkClubStr->fetch () ) {
				$this->teamId = $row ['club_id'];
			}
		}
	}
	public function setFavoriteTeam($favoriteTeam) {
		if ($favoriteTeam == "" || $favoriteTeam == null) {
			$this->messages ['favorite-team'] = "Въведете любим отбор!";
			$this->state = false;
			return;
		}
		
		$this->favoriteTeam = $favoriteTeam;
	}
	public function setFavTeamId($favoriteTeam) {
		$connection = DBConnection::getDBConnection ();
		
		$checkFavClub = "SELECT club_id
				      FROM club
				      WHERE club_name = :CLUB_STR";
		
		$checkFavClubStr = $connection->prepare ( $checkFavClub );
		$checkFavClubStr->bindValue ( ":CLUB_STR", $favoriteTeam, PDO::PARAM_STR );
		$checkFavClubStr->execute ();
		$this->favTeamId = 0;
		
		while ( $row = $checkFavClubStr->fetch () ) {
			$this->favTeamId = $row ['club_id'];
		}
		if ($this->favTeamId == 0) {
			$insertFavClub = "INSERT INTO club (club_name ) VALUES (:CLUB_STR)";
			$insertFav = $connection->prepare ( $insertFavClub );
			$insertFav->bindValue ( ":CLUB_STR", $favoriteTeam, PDO::PARAM_STR );
			$insertFav->execute ();
			
			$checkFavClub = "SELECT club_id
				      FROM club
				      WHERE club_name = :CLUB_STR";
			
			$checkFavClubStr = $connection->prepare ( $checkFavClub );
			$checkFavClubStr->bindValue ( ":CLUB_STR", $favoriteTeam, PDO::PARAM_STR );
			$checkFavClubStr->execute ();
			
			while ( $row = $checkFavClubStr->fetch () ) {
				$this->favTeamId = $row ['club_id'];
			}
		}
	}
	public function validateForm() {
		// check password and repeat password
		if (($this->getPassword ()) != ($this->getRepeatPassword ())) {
			$this->messages ['password2'] = "Двете пароли не съвпадат!";
			$this->state = false;
			return;
		}
	}
	public function process() {
		// SQL command to enter the user in the database
		$this->token = $this->getUsername () . $this->getEmail ();
		
		$connection = DBConnection::getDBConnection ();
		
		$this->setCityId ( $this->getCity () );
		
		if (isset ( $request ['team'] )) {
			$this->setTeamId ( $this->getTeam () );
		} else {
			$this->setTeamId ( $this->getTeamId () );
		}
		$this->setFavTeamId ( $this->getFavoriteTeam () );
		$this->setLeagueId ( $this->getLeagueId () );
		
		$statement = "INSERT INTO User (user_name, email, active, city, favorite_club, playing, playing_club, password, reg_date, token)
		              VALUES (:USER_NAME, :EMAIL, :ACTIVE, :CITY, :FAVORITE_CLUB, :PLAYING, :PLAYING_CLUB, 
				              md5(:PASSWORD), NOW(), md5(:TOKEN))";
		
		$stmt = $connection->prepare ( $statement );
		
		$stmt->bindValue ( ":USER_NAME", $this->getUsername (), PDO::PARAM_STR );
		$stmt->bindValue ( ":EMAIL", $this->getEmail (), PDO::PARAM_STR );
		$stmt->bindValue ( ":ACTIVE", $this->getFootballRole (), PDO::PARAM_STR );
		$stmt->bindValue ( ":CITY", $this->getCityId (), PDO::PARAM_INT );
		$stmt->bindValue ( ":FAVORITE_CLUB", $this->getFavTeamId (), PDO::PARAM_INT );
		$stmt->bindValue ( ":PLAYING", $this->getLeagueId (), PDO::PARAM_INT );
		$stmt->bindValue ( ":PLAYING_CLUB", $this->getTeamId (), PDO::PARAM_INT );
		$stmt->bindValue ( ":PASSWORD", $this->getPassword (), PDO::PARAM_STR );
		$stmt->bindValue ( ":TOKEN", $this->token, PDO::PARAM_STR );
		
		$stmt->execute ();
		
	$this->sendMail();
	header( "Location: registrationSuccessful.php");
	}
	
	public function sendMail(){
		$host = $_SERVER['host'];
		$confirmationLink = "http://$host/PDO/HW/confirmUser.php?user=$this->token";
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$subject = '<html>
<head>
<title>Confirmation Link</title>
</head>
<body>
Regstration link: <a href="' . $confirmationLink . '">Click Here</a>
</body>
</html>';
		mail ( $this->email, "Registration", $subject, 'From: alabala@alabala.com', $headers );
	}
}
	
